#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
//int sigaction(int signum, const struct sigaction *act,struct sigaction *oldact);
void catch_sig(int num)
{
        printf("catch signal %d\n", num);
        int status;
        pid_t wpid ;
        while((wpid = waitpid(-1, &status, WNOHANG)) > 0){
                if(WIFEXITED(status)){
                        printf("孩子%d return value:%d\n", wpid, WEXITSTATUS(status));
                }
                if(WIFSIGNALED(status)){
                        printf("孩子%d died by signal:%d\n",  wpid, WTERMSIG(status));
                }
        }
}
int main(int argc, char const *argv[])
{
        int i = 0;
        pid_t pid;
        //在创建子进程之前屏蔽SIGCHLD信号
        sigset_t myset,oldset;
        sigemptyset(&myset);
        sigaddset(&myset, SIGCHLD);
        //oldset保留现场,设置了SIGCHLD到阻塞信号集
        sigprocmask(SIG_BLOCK,&myset,&oldset);
        for (i = 0; i < 10; i++){
                pid = fork();
                if(pid == 0){
                        break;
                }
        }
        if(i == 10){
                //parent
                struct sigaction act;
                act.sa_flags = 0;
                sigemptyset(&act.sa_mask);
                act.sa_handler =  catch_sig;
                sigaction(SIGCHLD, &act, NULL);
                //解除屏蔽
                sigprocmask(SIG_SETMASK,&oldset,NULL);
                while (1){
                        sleep(1);
                }
        }else if(i < 10){
                printf("孩子%d\n",getpid());
        }
        return 0;
}
